import { defineStore } from 'pinia'
import { ref } from 'vue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'
import { appoxUtility } from '@/appox/appox'
import { AppoxSecondProfilePack } from '@/appox/appox'

export const useOtherChannelsStore = defineStore('otherChannels', () => {
  // 状态
  const samplesText = ref('')
  const generalRawDataText = ref('')
  const isUpdating = ref(false)

  // 数据
  let sampleSecondProfileBuffers = {'audio': []}
  let rawDataProtocolFlags = {}

  // 动作
  function initializeOtherChannels() {
    // 初始化其他通道面板
    samplesText.value = ''
    generalRawDataText.value = ''
  }

  async function updateOtherChannels() {
    if (isUpdating.value) return
    isUpdating.value = true

    let running = await agencyAsync.getAppStatus() == appoxEnums.ApplicationStatus.Running

    if (!running) {
      samplesText.value = ''
      generalRawDataText.value = ''
      isUpdating.value = false
      return
    }

    let interest = appoxUtility.getInterestTimeLocal()
    let availableSampleChannels = await agencyAsync.getAvailableSampleChannels() || []
    let availableRawDataChannels = await agencyAsync.getAvailableRawChannels() || []

    for (let i = 0; i < availableSampleChannels.length; i++) {
      let channelID = availableSampleChannels[i]
      if (sampleSecondProfileBuffers[channelID] == null) {
        sampleSecondProfileBuffers[channelID] = []
      }
    }

    for (let i = 0; i < availableRawDataChannels.length; i++) {
      let channelID = availableRawDataChannels[i]
      rawDataProtocolFlags[channelID] = true
    }

    let samplePromises = {}
    for (const channelID in sampleSecondProfileBuffers) {
      if (channelID == 'audio') {
        samplePromises[channelID] = agencyAsync.getAudioChannelStatus(1000)
      }
      else {
        samplePromises[channelID] = agencyAsync.getSampleChannelStatus(channelID, 1000)
      }
    }
    const sampleStatusResults = await Promise.all(Object.values(samplePromises))
    let sampleStatusText = ''
    let i = 0
    for (const channelID in samplePromises) {
      let searchResult = appoxUtility.searchSample(sampleSecondProfileBuffers[channelID], interest, 1.0)
      if (searchResult) {
        let secondProfile = searchResult.weight1 > searchResult.weight2 ? searchResult.sample1 : searchResult.sample2
        sampleStatusText += `${channelID}: ${secondProfile.availableCount} / ${secondProfile.sourceCount}\n`
      } else {
        sampleStatusText += `${channelID}: ${sampleStatusResults[i] && sampleStatusResults[i][0] ? 'O' : 'X'}\n`
      }
      i++
    }
    samplesText.value = sampleStatusText

    let rawDataPromises = {}
    for (const channelID in rawDataProtocolFlags) {
      rawDataPromises[channelID] = agencyAsync.getRawChannelStatus(channelID, 1000)
    }
    const rawDataStatusResults = await Promise.all(Object.values(rawDataPromises))
    let rawDataStatusText = ''
    let j = 0
    for (const channelID in rawDataPromises) {
      rawDataStatusText += `${channelID}: ${rawDataStatusResults[j] ? 'O' : 'X'}\n`
      j++
    }
    generalRawDataText.value = rawDataStatusText
    

    isUpdating.value = false
  }

  function onResetData() {
    sampleSecondProfileBuffers = {'audio': []}
    rawDataProtocolFlags = {}
  }

  function onInputData(data) {
    if (data instanceof AppoxSecondProfilePack) {
      for (const [channelID, sample] of Object.entries(data.profiles)) {
        if (sampleSecondProfileBuffers[channelID] != null) {
          sampleSecondProfileBuffers[channelID].push(sample)
        }
      }
    }
  }

  return {
    // 状态
    samplesText,
    generalRawDataText,
    // 动作
    initializeOtherChannels,
    updateOtherChannels,
    onResetData,
    onInputData
  }
}) 